<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never"> 试题录入/编辑 </el-card>
      <el-card shadow="always">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <!-- 学科 -->
          <el-form-item
            required=""
            v-model="form.subjectID"
            label="学科"
            prop="subjectID"
          >
            <el-select
              style="width: 400px"
              v-model="form.subjectID"
              placeholder="请选择"
              @change="active"
            >
              <el-option
                v-for="sub in lists"
                :key="sub.id"
                :label="sub.label"
                :value="sub.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item required="" label="目录" prop="catalogID">
            <el-select
              style="width: 400px"
              v-model="form.catalogID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in catalogList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item
            required=""
            v-model="form.enterpriseID"
            label="企业"
            prop="enterpriseID"
          >
            <el-select
              style="width: 400px"
              v-model="form.enterpriseID"
              placeholder="请选择"
            >
              <el-option
                v-for="com in companys"
                :key="com.id"
                :label="com.shortName"
                :value="com.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item required="" label="城市" prop="province">
            <el-select
              v-model="form.province"
              style="width: 200px"
              placeholder="请选择"
              @change="getCity(form.province)"
            >
              <el-option
                v-for="item in province"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              style="width: 200px"
              v-model="form.city"
              placeholder="请选择"
            >
              <el-option
                v-for="item in city"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item
            required=""
            v-model="form.direction"
            label="方向"
            prop="direction"
          >
            <el-select
              style="width: 400px"
              v-model="form.direction"
              placeholder="请选择"
            >
              <el-option
                v-for="item in directions"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item required="" label="题型" prop="questionType">
            <el-radio-group v-model="form.questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item required="" label="难度" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item required="" label="题干" prop="question">
            <quill-editor
              v-model="form.question"
              :content="content"
              :options="editorOption"
            />
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项" v-if="form.questionType != 3">
            <!-- 1.单选题 -->
            <template v-if="form.questionType == 1">
              <el-row v-for="item in SelList" :key="item.code">
                <el-col :span="1" :offset="0">
                  <el-radio :label="item.code" v-model="options"></el-radio>
                </el-col>
                <el-col :span="8">
                  <el-input
                    v-model="form.title"
                    placeholder="请输入选项"
                  ></el-input>
                </el-col>
                <el-col :span="10">
                  <el-upload
                    class="avatar-uploader"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    <span>上传图片</span>
                  </el-upload>
                </el-col>
              </el-row>
              <el-button
                type="danger"
                @click="addSel"
                :disabled="form.questionType != 2"
                >+增加选项与答案</el-button
              >
              <el-button
                type="danger"
                @click="delSel"
                :disabled="form.questionType != 2"
                >删除</el-button
              >
            </template>
            <!-- 2.多选题 -->
            <template v-if="form.questionType == 2">
              <el-checkbox-group v-model="options">
                <el-row v-for="item in checkboxOptionList" :key="item.code">
                  <el-col :span="1" :offset="0">
                    <el-checkbox :label="item.code"></el-checkbox>
                  </el-col>
                  <el-col :span="8">
                    <el-input
                      v-model="item.title"
                      placeholder="请输入选项"
                    ></el-input>
                  </el-col>
                  <el-col :span="10">
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                    >
                      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <span>上传图片</span>
                    </el-upload>
                  </el-col>
                </el-row>
                <el-button
                  type="danger"
                  @click="addSel"
                  :disabled="form.questionType != 2"
                  >+增加选项与答案</el-button
                >
                <el-button
                  type="danger"
                  @click="delSel"
                  :disabled="form.questionType != 2"
                  >删除</el-button
                >
              </el-checkbox-group>
            </template>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频">
            <el-input
              v-model="form.videoURL"
              placeholder=""
              size="normal"
              clearable
            ></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item required="" label="答案解析" prop="answer">
            <quill-editor
              v-model="form.answer"
              :content="content"
              :options="editorOption"
            />
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注">
            <el-input type="textarea" v-model="form.remarks"></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签">
            <el-select
              class="selopt"
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
            >
              <el-option
                v-for="item in options"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 确认提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">{{
              show ? "确认提交" : "确认修改"
            }}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// require styles 引入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/companys.js'
import { simple as Catelog } from '@/api/hmmm/directorys.js'
import { direction } from '@/api/hmmm/constants.js'
import { add, update, detail as back } from '@/api/hmmm/questions.js'
import { detail } from '@/api/hmmm/tags.js'
import { provinces, citys } from '@/api/hmmm/citys.js'

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  ['blockquote', 'code-block'], // 引用  代码块
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  ['image', 'link'] // 链接、图片、视频
]
export default {
  name: 'New',
  components: { quillEditor },
  data () {
    return {
      rules: {
        subjectID: [
          { required: true, message: '学科不可以为空', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '目录不可以为空', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '企业不可以为空', trigger: ['blur', 'change'] }
        ],
        city: [
          { required: true, message: '城市不能为空', trigger: ['blur', 'change'] }
        ],
        province: [
          { required: true, message: '城市不能为空', trigger: ['blur', 'change'] }
        ],
        question: [
          { required: true, message: '题干不能为空', trigger: ['blur', 'change'] }
        ],
        answer: [
          { required: true, message: '答案解析不能为空', trigger: ['blur', 'change'] }
        ],
        direction: [
          { required: true, message: '方向不能为空', trigger: ['blur', 'change'] }
        ],
        questionType: [
          { required: true, message: '题型至少选一个', trigger: ['blur', 'change'] }
        ],
        difficulty: [
          { required: true, message: '难度至少选一个', trigger: ['blur', 'change'] }
        ]
      },
      // 城市选择--数据字典
      provinces,
      citys,
      // 接口数组
      province: [],
      city: [],
      // 单选题答案
      radioAnswer: '',
      // 多选题答案
      checkedAnswerList: [],
      // 题目备注
      remarks: '',
      // 按钮禁用状态
      disabled: true,
      // 学科ID
      subjectID: '',
      // 学科ID
      subId: '',
      // 上传图片地址
      imageUrl: '',
      // dialogImageUrl: '',
      // dialogVisible: false,
      // 题干属性值
      content: '',
      // 题干/答案解析
      editorOption: {
        placeholder: '请输入文本...',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      // 目录列表
      catalogList: [],
      // 学科列表
      lists: [],
      // 企业列表
      companys: [],
      // 方向列表
      directions: [],
      // 选项列表
      SelList: [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ],
      // 多选题选项列表
      checkboxOptionList: [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ],
      num1: 4,
      num2: 68,
      // 标签选择器
      options: [],
      // value: [],
      // button显示
      show: true,

      // 表单数据
      form: {
        // 学科列表
        subjectID: null,
        // 目录列表
        catalogID: null,
        // 企业列表
        enterpriseID: null,
        // 方向列表
        direction: null,
        // 题型单选
        questionType: '1',
        // 难易
        difficulty: '1',
        // 题干
        question: null,
        // 答案解析
        answer: null,
        // 解析视频
        videoURL: null,
        // 城市
        province: null,
        // 地区
        city: null,
        tags: [],
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      }
    }
  },
  watch: {
    $route: {
      immediate: true, // 立即执行
      handler: function (route) {
        console.log('监听', route)
        if (route.fullPath === '/questions/new') {
          this.show = true
          this.form = {
            // 目录
            catalogID: null,
            // 学科列表
            subjectID: null,
            // 企业列表
            enterpriseID: null,
            // 方向列表
            direction: null,
            // 题型单选
            questionType: '1',
            // 难易
            difficulty: '1',
            // 题干
            question: null,
            // 答案解析
            answer: null,
            // 解析视频
            videoURL: null,
            // 城市
            province: null,
            // 地区
            city: null,
            tags: [],
            // 选项
            options: [
              // { isRight: false, code: 'A', title: '', img: '' },
              // { isRight: false, code: 'B', title: '', img: '' },
              // { isRight: false, code: 'C', title: '', img: '' },
              // { isRight: false, code: 'D', title: '', img: '' }
            ]
          }
        } else {
          this.show = false
          this.backdata()
        }
      }
    }

  },
  created () {
    this.getList()
    this.getCompanys()
    this.getDirection()
    this.province = provinces()
    // console.log('参数id取得', this.$route.query.id)
  },
  methods: {
    // 数据回填
    async backdata () {
      // console.log('查看id', this.$route.query.id)
      const formdetail = await back(this.$route.query)
      console.log('数据回显', formdetail.data)
      // console.log('select标签', formdetail.data.tags)
      // console.log('select标签', formdetail.data.tags.split(' '))
      formdetail.data.tags = formdetail.data.tags.split(',')
      this.form = formdetail.data
    },
    // 表单提交
    onSubmit () {
      console.log(this.form)
      // const tag = this.form.tags.join(',')
      this.$refs.form.validate(async (isOk) => {
        if (isOk) {
          if (this.form.id) {
            // 编辑状态
            // const res = await update({ ...this.form, tags: tag }, this.form.id)
            if (!this.form.videoURL) {
              this.form.videoURL = '空'
            }
            if (!this.remarks) {
              this.remarks = '空'
            }
            const str = this.form.tags.join(',') || ''
            const res = await update({ ...this.form, remarks: this.remarks, tags: str })
            console.log('修改试题', res)
            this.$message.success('表单修改成功！')
            this.form = {
              // 学科列表
              subjectID: null,
              // 企业列表
              enterpriseID: null,
              // 方向列表
              direction: null,
              // 题型单选
              questionType: '1',
              // 难易
              difficulty: '1',
              // 题干
              question: null,
              // 答案解析
              answer: null,
              // 解析视频
              videoURL: null,
              // 城市
              province: null,
              // 地区
              city: null,
              tags: [],
              // 选项
              options: [
                { isRight: false, code: 'A', title: '', img: '' },
                { isRight: false, code: 'B', title: '', img: '' },
                { isRight: false, code: 'C', title: '', img: '' },
                { isRight: false, code: 'D', title: '', img: '' }
              ]
            }
            this.$router.back()
          } else {
            // 新增状态
            // await add({ ...this.form, tags: tag })
            const str = this.form.tags.join(',')
            this.form.tags = null
            await add({ ...this.form, tags: str })
            this.$message.success('表单提交成功！')
            this.$router.push('list')
          }
        } else {
          return false
        }
      })
    },
    // 学科数据获取
    async getList () {
      const { data: res } = await simple()
      console.log('学科获取', res)
      this.lists = res
      this.getTags()
    },
    active (subId) {
      // console.log('12', subId)
      this.getCatalog(subId)
      this.getTags(subId)
      this.form.catalogID = ''
    },
    // 目录获取
    async getCatalog (subId) {
      console.log('目录id', subId)
      const res = await Catelog({ subjectID: subId })
      // const res = await Catelog()
      console.log('目录', res.data)
      this.catalogList = res.data
      // console.log(this.catalogList)
    },
    // 企业列表获取
    async getCompanys () {
      const { data: res } = await list()
      console.log('企业列表', res)
      this.companys = res.items
    },
    // 方向列表获取
    getDirection () {
      // console.log('数据字典', direction)
      // const directions = [...direction]
      // console.log('新数组', directions)
      this.directions = direction
    },
    // 试题标签获取
    async getTags (subId) {
      console.log('标签id', subId)
      const { data: res } = await detail({ id: subId })
      console.log('标签', res.data)
      // this.options = res.data
      if (!res.tagName) {
        return
      }
      this.options.push(res.tagName)
    },
    // 按钮增加选项
    addSel () {
      this.num1++
      this.num2++
      console.log(this.num1, this.num2)
      const option = String.fromCharCode(this.num2)
      this.checkboxOptionList.push({
        code: option,
        title: '',
        isRight: false,
        img: ''
      })
    },
    // 城市获取
    getCity (value) {
      this.form.city = null
      this.city = this.citys(value)
    },
    // 按钮删除
    delSel () {
      this.num1--
      this.num2--
      this.checkboxOptionList.pop()
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .ql-editor {
  height: 200px;
}
::v-deep .filter-item {
  width: 183px;
}

.el-row {
  margin-bottom: 20px;
  height: 50px;
  line-height: 50px;
  &:last-child {
    margin-bottom: 0;
  }
}
::v-deep .avatar-uploader .el-upload {
  width: 100px;
  height: 40px;
  line-height: 40px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
}
.optInt {
  width: 400px;
  // margin-left: 50px;
}
::v-deep .el-radio {
  width: 40px;
  height: 50px;
  line-height: 50px;
}
.el-checkbox {
  width: 40px;
  margin-right: 30px;
}
.selopt {
  width: 400px;
}
::v-deep .el-checkbox-group {
  font-size: 14px;
}
</style>
